#!/bin/bash
#this is intended to be run on the router
HOST=localhost
NC='nc'
PORT=$(ls /dev/ttyACM*)
COMMAND_DELIMITER='%'

if [ -z "$(pgrep mpd)" ]; then
	echo "mpd NOT running. Exiting..."
	exit
fi

if [ "$1" != "" ]; then
	HOST="$1"
fi
echo "Running for host $HOST"
echo "Port $PORT"

function clean_up() {
	# Perform program exit housekeeping
	echo "Shutting down..."
	PIDOFMPC=$(pidof mpc)
	kill -9 $PIDOFMPC &>/dev/null
	exit
}

trap clean_up SIGHUP SIGINT SIGTERM

function sendToPort() {
	local COMMAND=$1
	local VALUE=$2
	echo "$COMMAND$COMMAND_DELIMITER${VALUE}" > $PORT
}

function volumeAction() {
	local volume=$1
	echo "VOLUME $volume"
	sendToPort "VOLUME" "$volume"
}

function stateAction() {
	local state=$1
	echo "STATE $state"
	sendToPort "STATE" "$state"
}

function outputTrack() {
	local title=$1
	local artist=$2
	local name=$3
	local final=""
	echo -n "TITLE "
	if [ -n "$title" ] || [ -n "$artist" ]; then
		if [ -n "$artist" ]; then
			echo -n "[ $artist ] "
			final="$final[ $artist ] "
		fi
		echo "$title"
		final="$final$title"
	else
		echo "$name"
		final="$final$name"
	fi
	sendToPort "TITLE" "$final"
}

function handleChangeEvent() {
	eventType=$1
	STATUS=$(echo "status" | ${NC} $HOST 6600) 
	if [ "$eventType" == "mixer" ]; then
		volume=$(echo "$STATUS" | grep "volume" | cut -d ":" -f2 | tr -d " ")
		if [[ "$volume" != "$prevvolume" ]]; then
			volumeAction "$volume"	
			prevvolume="$volume"
		fi
	fi
	if [ "$eventType" == "player" ]; then
		currtrack="$(mpc -h $HOST -f "%artist% %title% %name%" current)"
		if [[ "$currtrack" != "$prevtrack" ]]; then
			title="$(mpc -h $HOST -f '%title%' current)"
			artist="$(mpc -h $HOST -f '%artist%' current)"
			name="$(mpc -h $HOST -f '%name%' current)"
			outputTrack "$title" "$artist" "$name"
			prevtrack="$currtrack"
		fi
		playstate=$(echo "$STATUS" | grep "state" | cut -d ":" -f2 | tr -d " ")	
		if [[ "$playstate" != "$prevplaystate" ]]; then
			stateAction "$playstate"
			prevplaystate="$playstate"
		fi
	fi
}

volumeAction 0
handleChangeEvent "mixer"
handleChangeEvent "player"

( while read -r line; do
	handleChangeEvent $line
    done < <(mpc -h $HOST idleloop player mixer) )
